package com.dx.oa.sysmng.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.entity.Menu;
import com.dx.oa.sysmng.mapper.MenuMapper;
import com.dx.oa.sysmng.mapper.RoleMapper;
import com.dx.oa.sysmng.mapper.UserMapper;
import com.dx.oa.sysmng.service.IMenuService;

@Service
public class MenuService implements IMenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	public List<Menu> getMenuList() {
		// TODO Auto-generated method stub
		return menuMapper.getMenuList();
	}
	
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public int deleteMenuById(Integer menuId) {
		// TODO Auto-generated method stub
		
		int row = roleMapper.deleteMenuRoleByMenuId(menuId);
		if(row < 0)
			return 0;
		return menuMapper.deleteMenuById(menuId);	
	}

	public int getChildCnt(Integer menuId) {
		// TODO Auto-generated method stub
		return menuMapper.getChildCnt(menuId);
	}

	public Menu getMenuById(Integer menuId) {
		// TODO Auto-generated method stub
		return menuMapper.getMenuById(menuId);
	}

	/**
	 * 需要新增超级管理员与之映射
	 */
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public int insertMenu(Menu menu) {
		// TODO Auto-generated method stub
		//roleMapper.
		int row = menuMapper.insertMenu(menu);
		if(row < 1)
			return 0;
		Map<String,Object> para  = new HashMap<String,Object>();
		para.put("roleId", 1);
		para.put("menulist", new Integer[]{menu.getId()});
		row = roleMapper.addRoleToMenuBatch(para);
		int nowid = UserUtils.getCurrentUserId();
		try {
			Long trid = userMapper.getRoleListByUserId(nowid).get(0);
			if(trid != null && trid != 1)
			{
				para.put("roleId", trid);
				row = roleMapper.addRoleToMenuBatch(para);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			if(row < 1)
				return 0;
			return 1;
		}
	}

	public int updateMenu(Menu menu) {
		// TODO Auto-generated method stub
		return menuMapper.updateMenu(menu);
	}

	public List<Menu> getMenuListById(Integer userId) {
		// TODO Auto-generated method stub
		return menuMapper.getMenuListByUserId(userId);
	}




}
